﻿//=====================================================
// Copyright © 2017-2018 xuxuzhaozhao
// All rights reserved
// GUID: 2be2b624-79cf-4c40-b8a2-6b49edcd7c91
// CLR版本: 4.0.30319.42000
// 新建项输入的名称: Repository
// 机器名称: WIN10-20170502F
// 注册组织名: 成都名门汇科技有限公司（谊诚科技）
// 命名空间名称: UnitTestingWebAPI.Data.Infrstucture
// 文件名: Repository
// 当前系统时间: 2017/10/21 17:26:55
// 当前登录用户名: xuxuzhaozhao
//======================================================

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace UnitTestingWebAPI.Data.Infrstucture
{
    public abstract class RepositoryBase<T> where T : class
    {
        #region Properties
        private BloggerEntities _dataContext;
        private readonly IDbSet<T> _dbSet;

        protected IDbFactory DbFactory
        {
            get;
            private set;
        }

        protected BloggerEntities DbContext => _dataContext ?? (_dataContext = DbFactory.Init());

        #endregion

        protected RepositoryBase(IDbFactory dbFactory)
        {
            DbFactory = dbFactory;
            _dbSet = DbContext.Set<T>();
        }

        #region Implementation
        public virtual void Add(T entity)
        {
            _dbSet.Add(entity);
        }

        public virtual void Update(T entity)
        {
            _dbSet.Attach(entity);
            _dataContext.Entry(entity).State = EntityState.Modified;
        }

        public virtual void Delete(T entity)
        {
            _dbSet.Remove(entity);
        }

        public virtual void Delete(Expression<Func<T, bool>> where)
        {
            IEnumerable<T> objects = _dbSet.Where<T>(where).AsEnumerable();
            foreach (T obj in objects)
                _dbSet.Remove(obj);
        }

        public virtual T GetById(int id)
        {
            return _dbSet.Find(id);
        }

        public virtual IEnumerable<T> GetAll()
        {
            return _dbSet.ToList();
        }

        public virtual IEnumerable<T> GetMany(Expression<Func<T, bool>> where)
        {
            return _dbSet.Where(where).ToList();
        }

        public T Get(Expression<Func<T, bool>> where)
        {
            return _dbSet.Where(where).FirstOrDefault<T>();
        }

        #endregion

    }
}
